#include "purchase.h"
#include "ui_purchase.h"
#include <QDebug> // 添加调试输出

purchase::purchase(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::purchase),
    price(0) // 初始化价格为0
{
    ui->setupUi(this);

    // 设置lineEdit为只读
    ui->lineEdit->setReadOnly(true);

    // 设置spinBox范围
    ui->spinBox->setRange(1, 99);
    ui->spinBox->setValue(1); // 默认数量为1

    // 连接spinBox的值变化信号到槽函数（使用更可靠的连接方式）
    connect(ui->spinBox, SIGNAL(valueChanged(int)), this, SLOT(on_spinBox_valueChanged(int)));

    // 初始显示总价
    on_spinBox_valueChanged(1); // 使用初始值1

    qDebug() << "Purchase window created. Initial price:" << price;
}

purchase::~purchase()
{
    delete ui;
}

void purchase::setPrice(int p)
{
    price = p;
    qDebug() << "Price set to:" << price;

    // 立即更新总价显示
    on_spinBox_valueChanged(ui->spinBox->value());

    // 发出信号用于调试
    emit priceSet(price);
}

void purchase::on_spinBox_valueChanged(int value)
{
    // 计算总价
    int total = price * value;

    // 在lineEdit中显示总价
    ui->lineEdit->setText(QString::number(total));

    // 调试输出
    qDebug() << "SpinBox value changed to:" << value
             << "| Price:" << price
             << "| Total:" << total;
}

void purchase::on_pushButton_clicked()
{
    // 显示父窗口
    if (QWidget *parent = this->parentWidget()) {
        parent->show();
    }

    // 关闭当前窗口
    this->close();
}
